<template>
  <div class="order-page">
    <div class="order-table">
      <Table
        ref="tableRef"
        :columns="tableColumns"
        :options="{
          headerFixed: true,
          minWidth: 120,
          setting: { show: true, storage: true, storageKey: 'order_table' },
          searchSetting: { show: true, storage: true, storageKey: 'order_table_search', title: '订单' }
          // virtual: { type: 'fix', options: { height: 138, bufferNumber: 2, offsetTop: 45 } }
        }"
        :api="getOrderQueryPage"
        :after-api-transform-data="afterApiTransformData"
        :pagination="pagination"
        @row-click="rowClickHandler"
      >
        <template #tool-right>
          <el-button type="primary" v-auth="'add'" class="mr30" :icon="Plus" @click="openDialog">新增</el-button>
        </template>
        <template #name="{ scope }">
          <div class="wik-column-client">
            <el-icon><Files /></el-icon>
            <span class="sle">{{ scope.name }}</span>
          </div>
        </template>
        <template #agvType="{ scope }">
          <div class="wik-column">
            <div class="wik-column-item" v-for="item in scope.agvType" :key="item.id">{{ item.name }}</div>
          </div>
        </template>
        <template #agvCountCustom="{ scope }">
          <div class="wik-column">
            <div class="wik-column-item" v-for="item in scope.agvCountCustom" :key="item.id">{{ item.name }}</div>
          </div>
        </template>
        <template #productionFactoryId="{ scope }">
          <div class="wik-column">
            <div class="wik-column-item" v-for="item in scope.productionFactoryId" :key="item.id">
              {{ getDictItem("productionFactory", item.factoryId) }}
            </div>
          </div>
        </template>
        <template #controllerId="{ scope }">
          <div class="wik-column">
            <div class="wik-column-item" v-for="item in scope.controllerId" :key="item.id">
              {{ controllerList.find(im => im.id === item.controllerId)?.name || "--" }}
            </div>
          </div>
        </template>
        <template #[item]="{ scope }" v-for="item in timeColumnTemplateList" :key="item">
          <div class="wik-column">
            <AuthTable
              :permissions="resourceButton"
              :key-string="item"
              v-for="im in Array.isArray(scope[item]) ? scope[item] : [{ id: '', name: scope[item] }]"
              :key="im.id"
            >
              <template #edit>
                <!-- 计划时间只允许修改一次, 实际时间只能选择今天昨天前天 -->
                <TriggerContext
                  class="trigger-context-status wik-column-item"
                  v-if="!PLAN_TIME_LIST.includes(item) || (!scope[item] && PLAN_TIME_LIST.includes(item))"
                  :component="Calendar"
                  :props="{
                    'selected-Date': im.name,
                    attribute: {
                      disabledDate: (date: any) => {
                        if (TIME_LIST.includes(item)) {
                          const today = new Date().setHours(0, 0, 0, 0);
                          const tomorrow = today - 24 * 3600 * 1000 * 2; // 昨天的日期
                          return (
                            date.getTime() < tomorrow || // 早于今天
                            date.getTime() > today // 晚于 昨天
                          );
                        }
                      }
                    },
                    handleDateChange: async (date: any) => {
                      editHandler({
                        projectId: scope.projectId,
                        orderId: scope.id,
                        orderProductId: im.id || undefined,
                        tableName: getTableName(item),
                        fieldName: item,
                        newValue: date
                      });
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <span class="order-table-name">{{ formatHandler(im.name) }}</span>
                    <svg-icon name="rl"></svg-icon>
                  </div>
                </TriggerContext>
                <span class="order-table-name wik-column-item" v-if="PLAN_TIME_LIST.includes(item) && scope[item]">{{
                  formatHandler(im.name)
                }}</span>
              </template>
              <template #get>
                <span class="order-table-text wik-column-item">{{ formatHandler(im.name) }}</span>
              </template>
            </AuthTable>
          </div>
        </template>
        <template #[item]="{ scope }" v-for="item in delayContentColumns" :key="item">
          <div class="wik-column">
            <!--         v-if="im.name !== undefined && im.name !== null" -->
            <template v-for="im in Array.isArray(scope[item]) ? scope[item] : [{ id: '', name: scope[item] }]" :key="im.id">
              <div class="wik-column-item flx-center">
                <div class="order-table-status-delay" :class="{ 'order-table-status-delay_active': im.name }">
                  {{ im.name ? "延期" : "正常" }}
                </div>
              </div>
            </template>
          </div>
        </template>
        <template #[item]="{ scope }" v-for="item in delayTimeColumns" :key="item">
          <div class="wik-column">
            <template v-for="im in Array.isArray(scope[item]) ? scope[item] : [{ id: '', name: scope[item] }]" :key="im.id">
              <span class="order-table-name wik-column-item">{{ im.name ? im.name + "日" : "--" }}</span>
            </template>
          </div>
        </template>
        <template #[item]="{ scope }" v-for="item in userColumns" :key="item">
          <div class="wik-column">
            <AuthTable :permissions="resourceButton" :key-string="item" v-for="im in scope[item]" :key="im.id">
              <template #edit>
                <TriggerContext
                  class="trigger-context-status wik-column-item"
                  :component="People"
                  :props="{
                    id: im.id,
                    list: userList,
                    handleDateChange: (date: any) => {
                      editHandler({
                        projectId: scope.projectId,
                        orderId: scope.id,
                        tableName: getTableName(item),
                        orderProductId: im.orderProductId,
                        fieldName: 'userName',
                        typeId: im.typeId,
                        newValueId: date,
                        newValue: userList.find((itm: any) => itm.id === date)?.name
                      });
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <span class="order-table-name">{{ userList.find(itm => itm.id === im.id)?.name }}</span>
                    <el-icon><User /></el-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text wik-column-item">{{ userList.find(itm => itm.id === im.id)?.name }}</span>
              </template>
            </AuthTable>
          </div>
        </template>
        <template #userId="{ scope }">
          <div class="wik-column">
            <AuthTable :permissions="resourceButton" key-string="userId">
              <template #edit>
                <TriggerContext
                  class="trigger-context-status"
                  :component="People"
                  :props="{
                    id: scope['userId'],
                    list: userList,
                    handleDateChange: (date: any) => {
                      editHandler({
                        projectId: scope.projectId,
                        orderId: scope.id,
                        tableName: getTableName('userId'),
                        fieldName: 'userName',
                        newValueId: date,
                        newValue: userList.find((itm: any) => itm.id === date)?.name
                      });
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <span class="order-table-name">{{ userList.find((itm: any) => itm.id === scope["userId"])?.name }}</span>
                    <el-icon><User /></el-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text">{{ userList.find((itm: any) => itm.id === scope["userId"])?.name }}</span>
              </template>
            </AuthTable>
          </div>
        </template>
        <template #status="{ scope }">
          <AuthTable :permissions="resourceButton" key-string="orderStatus">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope.status,
                  list: dealOrderStatus(getDict('orderStatus')),
                  handleDateChange: (date: any) => {
                    editHandler({
                      projectId: scope.projectId,
                      orderId: scope.id,
                      tableName: getTableName('status'),
                      fieldName: 'status',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="order-table-status" :class="colorOrderStatusMap[scope.status]">
                    {{ getDictItem("orderStatus", scope.status) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div v-show="scope.status" class="order-table-status" :class="colorOrderStatusMap[scope.status]">
                {{ getDictItem("orderStatus", scope.status) }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #stageId="{ scope }">
          <AuthTable :permissions="resourceButton" key-string="orderStatus">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope.stageId,
                  list: dealOrderStage(getDict('orderStage')),
                  handleDateChange: (date: any) => {
                    editHandler({
                      projectId: scope.projectId,
                      orderId: scope.id,
                      tableName: getTableName('stageId'),
                      fieldName: 'stageId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="order-table-status" :class="colorOrderStageMap[scope.stageId]">
                    {{ getDictItem("orderStage", scope.stageId) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div v-show="scope.status" class="order-table-status" :class="colorOrderStageMap[scope.stageId]">
                {{ getDictItem("orderStage", scope.status) }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #spStatus="{ scope }">
          <AuthTable :permissions="resourceButton" key-string="spStatus">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                type="dialog"
                :options="{
                  title: '审核状态',
                  width: '353px',
                  isShowFooter: false,
                  slots: {
                    default: () => h(Audit, { auditData: scope })
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="order-table-status" :class="SP_COLOR[scope.spStatus]">
                    {{ AUDIT_CONTENT[scope["spStatus"]] || "--" }}
                  </div>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div class="wik-column-rl">
                <div class="order-table-status" :class="SP_COLOR[scope.spStatus]">
                  {{ AUDIT_CONTENT[scope["spStatus"]] || "--" }}
                </div>
              </div>
            </template>
          </AuthTable>
        </template>
        <template #fileList="{ scope }">
          <TriggerContext
            class="trigger-context-status"
            type="dialog"
            :options="{
              title: '项目文档',
              width: '80vw',
              height: '80vh',
              isShowFooter: false,
              slots: {
                default: () => h(Document, { projectId: scope.projectId, resourceButton })
              }
            }"
          >
            <div class="order-table-document">查看</div>
          </TriggerContext>
        </template>
        <template #typeId="{ scope }">
          <span class="order-table-text">{{ getDictItem("orderType", scope["typeId"]) }}</span>
        </template>
        <template #sceneId="{ scope }">
          <span class="order-table-text">{{ getDictItem("scenario", scope["sceneId"]) }}</span>
        </template>
        <template #orderFollow="{ scope }">
          <span class="order-table-text default-pointer" @click.stop="rowClickHandler(scope, 5)">
            <s class="sle">{{ scope["orderFollow"][0]?.["content"] }}</s>
          </span>
        </template>
        <template #provinceCode="{ scope }">
          <span class="order-table-text sle">{{ scope["province"] }}</span>
        </template>
        <template #saleUserId="{ scope }">
          <span class="order-table-text sle"> {{ scope.saleUserName }}</span>
        </template>
        <template #implementRecord="{ scope }">
          <TriggerContext
            class="trigger-context-status"
            type="dialog"
            :options="{
              title: '实时记录表',
              width: '95vw',
              isShowFooter: false,
              slots: {
                default: () => h(ImplementRecord, { projectId: scope.projectId, resourceButton, orderId: scope.id, data: scope })
              }
            }"
          >
            <div class="order-table-document">查看</div>
          </TriggerContext>
        </template>
        <!-- <template #mechanicalDesignNumber="{ scope }">
          <AuthTable :permissions="resourceButton" key-string="mechanicalDesignNumber">
            <template #edit>
              <div class="wik-column-rl" @click.stop>
                <div class="order-table-status order-table-input">
                  <el-input
                    v-model="scope.mechanicalDesignNumber"
                    @change="
                      val =>
                        editHandler({
                          projectId: scope.projectId,
                          orderId: scope.id,
                          tableName: getTableName('mechanicalDesignNumber'),
                          fieldName: 'mechanicalDesignNumber',
                          newValue: val
                        })
                    "
                  ></el-input>
                </div>
                <el-icon><EditPen /></el-icon>
              </div>
            </template>
            <template #get>
              <span class="order-table-text">{{ scope.mechanicalDesignNumber }}</span>
            </template>
          </AuthTable>
        </template> -->
        <template #mechanicalDesignNumber="{ scope }">
          <div class="wik-column wik-column-over-auto">
            <AuthTable
              :permissions="resourceButton"
              key-string="mechanicalDesignNumber"
              v-for="im in Array.isArray(scope['mechanicalDesignNumber'])
                ? scope['mechanicalDesignNumber']
                : [{ id: '', name: scope['mechanicalDesignNumber'] }]"
              :key="im.id"
            >
              <template #edit>
                <TextArea
                  class="wik-column-item"
                  :value="im.name"
                  @change="
                    (val: any) =>
                      editHandler({
                        projectId: scope.projectId,
                        orderId: scope.id,
                        orderProductId: im.id || undefined,
                        tableName: getTableName('mechanicalDesignNumber'),
                        fieldName: 'mechanicalDesignNumber',
                        newValue: val || ''
                      })
                  "
                />
              </template>
              <template #get>
                <span class="track-table-text sle wik-column-item">{{ scope["mechanicalDesignNumber"] }}</span>
              </template>
            </AuthTable>
          </div>
        </template>
        <template #option="{ scope }">
          <div class="wik-table-option" @click.stop>
            <el-button v-auth="'delete'" type="text" @click="rowClickHandler(scope)">查看</el-button>
            <el-button v-auth="'delete'" type="text" @click="deleteOrderFn(scope)">删除</el-button>
          </div>
        </template>
      </Table>
    </div>
    <el-dialog
      v-model="detailVisible"
      width="80vw"
      :show-close="false"
      :append-to-body="true"
      class="order-detail-dialog"
      :align-center="true"
      @close="detailVisible = false"
      :z-index="1899"
    >
      <Detail v-if="detailVisible" v-bind="{ ...detailOptions }" v-model:detail-visible="detailVisible" />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, h, onMounted, reactive, provide } from "vue";
import { Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import Table from "@/components/Table/index.vue";
import { TableColumn } from "@/components/Table/interface";
import TriggerContext from "@/components/TriggerContext/index.vue";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import { Calendar, Status, People, Audit, Document, ImplementRecord, TextArea } from "./components/index";
import Detail from "./Detail.vue";
import AuthTable from "@/components/AuthTable/index.vue";

import { getResourceByUserId, getListAllUser, getProvince } from "@/api/modules/sys";
import { getProductModelList, getProductCategoryPartAll } from "@/api/modules/carType";
import { getOrderQueryPage, getOrderUpdate, deleteOrder } from "@/api/modules/order";
import { useHandleData } from "@/hooks/useHandleData";
import { ORDER_KEY } from "@/constants";
import { AUDIT_CONTENT, SP_COLOR, PLAN_TIME_LIST, TIME_LIST, AGV_MODEL_LIST } from "./constant"; // PLAN_TIME_LIST TIME_LIST

import { useAdd } from "./hooks/useAdd";
import { useDict } from "@/hooks/useDict";
const tableRef = ref<any>(null);
// const { BUTTONS } = useAuthButtons();

const { openDialog } = useAdd({ tableRef });

const { dict, getDictIdAsync, getDictId, getDictItem, getDict } = useDict([
  "scenario",
  "orderType",
  "orderStage",
  "orderStatus",
  "productionFactory"
]);

const detailVisible = ref(false);

const resourceButton = ref<any>({});

let detailOptions = reactive<any>({});

let userList = reactive<any>([]);
let controllerList = reactive<any>([]);

const tableColumns = ref<TableColumn[]>([]);

const pagination = ref({
  pageSize: 20,
  currentPage: 1,
  total: 0
});

provide("mainTableRef", tableRef);

// 时间内容列
const timeColumnTemplateList = ref<any>([
  "orderTime",
  "planPurchaseTime",
  "planMechanicalDesignTime",
  "planBomTime",
  "planElectricalSchematicsTime",
  "planWiringDiagramTime",
  "planProductionCompletedTime",
  "planCustomSoftwareDevelopmentTime",
  "planDebugCompletedTime",
  "planDeliveryTime",
  "planStartTime",
  "planEndTime",
  "purchaseTime",
  "mechanicalDesignTime",
  "bomTime",
  "electricalSchematicsTime",
  "wiringDiagramTime",
  "productionCompletedTime",
  "customSoftwareDevelopmentTime",
  "debugCompletedTime",
  "deliveryTime",
  "startTime",
  "endTime",
  "planFinishTime",
  "finishTime"
]);
// 延期内容列
const delayContentColumns = ref<any>([
  "purchaseDelay",
  "mechanicalDesignDelay",
  "bomDelay",
  "electricalSchematicsDelay",
  "wiringDiagramDelay",
  "productionCompletedDelay",
  "customSoftwareDevelopmentDelay",
  "debugCompletedDelay",
  "deliveryDelay",
  "orderDelay",
  "projectEndDelay",
  "projectStartDelay",
  "projectFinishDelay"
]);

// 用户内容列
const userColumns = ref<any>([
  "headOfDesign",
  "electricalDesign",
  "planUserId",
  "developId",
  "supportId"
  // "userId"
  // "saleUserId"
]);

// 延期天数
const delayTimeColumns = ref<any>([
  "purchaseDelayTime",
  "mechanicalDesignDelayTime",
  "bomDelayTime",
  "electricalSchematicsDelayTime",
  "wiringDiagramDelayTime",
  "productionCompletedDelayTime",
  "customSoftwareDevelopmentDelayTime",
  "debugCompletedDelayTime",
  "deliveryDelayTime",
  "projectStartDelayTime",
  "projectEndDelayTime",
  "projectFinishDelayTime"
]);
// 编辑订单
const editHandler = async (params: any) => {
  await getOrderUpdate(params);
  tableRef.value.refresh();
};

// 获取表名
const getTableName = (key: string) => {
  return tableColumns.value.find((item: any) => item.key === key)?.tableName;
};
const rowClickHandler = (val: any, tabIndex: any = 0) => {
  detailVisible.value = true;
  detailOptions = {
    orderId: val.id,
    projectId: val.projectId,
    resourceButton: resourceButton.value,
    tableColumns: tableColumns.value,
    tabIndex
  };
};

const tableColumnsOptions: any = {
  name: {
    width: 180,
    isFixed: true,
    className: "sle no-padding"
  },
  code: {
    width: 140
  },
  planPurchaseTime: {
    width: 220,
    className: "sle no-padding"
  },
  purchaseTime: {
    width: 220,
    className: "sle no-padding"
  },
  agvType: {
    className: "sle no-padding"
  },
  agvCountCustom: {
    className: "sle no-padding"
  },
  status: {
    // 订单状态
    className: "sle no-padding"
  },
  userId: {
    // 项目经理
    className: "sle no-padding"
  },
  saleUserId: {
    // 销售员
    className: "sle no-padding"
  },
  spStatus: {
    // 审批
    className: "sle no-padding"
  },
  fileList: {
    className: "sle"
  },
  planElectricalSchematicsTime: {
    width: 220,
    className: "sle no-padding"
  },
  electricalSchematicsTime: {
    width: 220,
    className: "sle no-padding"
  },
  planWiringDiagramTime: {
    width: 200,
    className: "sle no-padding"
  },
  wiringDiagramTime: {
    width: 200,
    className: "sle no-padding"
  },
  planProductionCompletedTime: {
    // 制造
    width: 240,
    className: "sle no-padding"
  },
  productionCompletedTime: {
    width: 240,
    className: "sle no-padding"
  },
  planMechanicalDesignTime: {
    width: 190,
    className: "sle no-padding"
  },
  mechanicalDesignTime: {
    width: 190,
    className: "sle no-padding"
  },
  planCustomSoftwareDevelopmentTime: {
    width: 220,
    className: "sle no-padding"
  },
  customSoftwareDevelopmentTime: {
    width: 220,
    className: "sle no-padding"
  },
  planDebugCompletedTime: {
    width: 180,
    className: "sle no-padding"
  },
  debugCompletedTime: {
    width: 180,
    className: "sle no-padding"
  },
  wiringDiagramDelay: {
    width: 180,
    className: "sle no-padding"
  },
  wiringDiagramDelayTime: { width: 160 },
  purchaseDelay: {
    width: 160,
    className: "sle no-padding"
  },
  purchaseDelayTime: {
    width: 160,
    className: "sle no-padding"
  },
  mechanicalDesignDelay: {
    // 机械图纸下发延期
    width: 160,
    className: "sle no-padding"
  },
  mechanicalDesignDelayTime: {
    // 机械图纸下发延期天数
    width: 160,
    className: "sle no-padding"
  },
  electricalSchematicsDelay: {
    // 电气原理图下发延期
    width: 180,
    className: "sle no-padding"
  },
  electricalSchematicsDelayTime: {
    width: 160,
    className: "sle no-padding"
    // 电气原理图下发延期天数
  },
  debugCompletedDelay: {
    // 调试完成延期
    width: 140,
    className: "sle no-padding"
  },
  debugCompletedDelayTime: {
    // 	调试完成延期天数
    width: 160,
    className: "sle no-padding"
  },
  orderTime: {
    // 	下单日期
    width: 160,
    className: "sle no-padding"
  },
  planDeliveryTime: {
    // 计划发货日期
    width: 180,
    className: "sle no-padding"
  },
  stageId: {
    // 阶段
    className: "sle no-padding",
    width: 140
  },
  orderDelayTime: {
    width: 180,
    className: "sle no-padding"
  },
  bomTime: {
    // BOOM
    width: 180,
    className: "sle no-padding"
  },
  planBomTime: {
    // BOOM计划完成
    width: 180,
    className: "sle no-padding"
  },
  bomDelay: {
    width: 180,
    className: "sle no-padding"
  },
  bomDelayTime: {
    width: 160,
    className: "sle no-padding"
  },
  headOfDesign: {
    // 设计主负责人
    className: "sle no-padding",
    width: 140
  },
  electricalDesign: {
    // 电气设计
    className: "sle no-padding"
  },
  planUserId: {
    // 规划设计
    className: "sle no-padding"
  },
  developId: {
    // 软件开发
    className: "sle no-padding"
  },
  supportId: {
    // 技术支持
    className: "sle no-padding"
  },
  mechanicalDesignNumber: {
    // 总图号
    width: 180,
    className: "no-padding"
  },
  productionFactoryId: {
    // 生产位置
    width: 120,
    className: "no-padding"
  },
  controllerId: {
    // 控制器
    className: "no-padding"
  },
  deliveryTime: {
    // 实际发货时间
    width: 180,
    className: "sle no-padding"
  },
  customSoftwareDevelopmentDelay: {
    // 开发延期
    width: 140,
    className: "sle no-padding"
  },
  productionCompletedDelay: {
    // 制造延期
    width: 140,
    className: "sle no-padding"
  },
  productionCompletedDelayTime: { width: 160, className: "sle no-padding" },
  deliveryDelay: {
    //发货延期
    width: 140,
    className: "sle no-padding"
  },
  deliveryDelayTime: {
    //延期天数
    width: 160,
    className: "sle no-padding"
  },
  provinceCode: {
    //省份
    width: 140
  },
  city: {
    //城市
    width: 140
  },
  sceneId: {
    //场景
    width: 160
  },
  orderFollow: {
    //订单跟踪
    className: "sle no-padding",
    width: 180
  },
  startTime: {
    //实际开始时间
    width: 220,
    className: "sle no-padding"
  },
  endTime: {
    // 实际验收时间
    width: 200,
    className: "sle no-padding"
  },
  planStartTime: {
    // 计划开始时间
    width: 220,
    className: "sle no-padding"
  },
  planEndTime: {
    // 计划验收时间
    width: 200,
    className: "sle no-padding"
  },
  projectStartDelay: {
    // 项目开始延期
    width: 140,
    className: "sle no-padding"
  },
  projectStartDelayTime: {
    // 项目开始延期天数
    width: 160,
    className: "sle no-padding"
  },
  projectEndDelay: {
    // 项目结束延期
    width: 140,
    className: "sle no-padding"
  },
  projectEndDelayTime: {
    // 项目结束延期天数
    width: 160,
    className: "sle no-padding"
  },
  customSoftwareDevelopmentDelayTime: {
    width: 160,
    className: "sle no-padding"
  },
  planFinishTime: {
    // 计划验收时间
    width: 200,
    className: "sle no-padding"
  },
  finishTime: {
    // 实际验收时间
    width: 200,
    className: "sle no-padding"
  },
  projectFinishDelay: {
    //验收延期
    width: 160,
    className: "sle no-padding"
  },
  projectFinishDelayTime: {
    //验收延期天数
    width: 160,
    className: "sle no-padding"
  }
};

/**
 * 筛选接口列表
 */
const filterFnList: any = {
  userList: async () => {
    const { data } = await getListAllUser({}, { noLoading: true });
    console.log(userList);
    return (
      (data &&
        data.map(item => {
          return {
            label: item.name,
            value: item.id
          };
        })) ??
      []
    );
  },
  carType: async () => {
    const { data } = await getProductModelList({}, { noLoading: true });
    return (
      (data &&
        data.map((item: any) => {
          return {
            label: item.name,
            value: item.id
          };
        })) ??
      []
    );
  },
  controllerId: async () => {
    const { data } = await getProductCategoryPartAll(
      {
        typeId: getDictId("control")
      },
      { noLoading: true }
    );
    return (
      (data &&
        data.map((item: any) => {
          return {
            label: item.name,
            value: item.id
          };
        })) ??
      []
    );
  },
  province: async () => {
    const { data } = await getProvince({});
    return (
      (data &&
        data.map((item: any) => {
          return {
            label: item.name,
            value: item.code
          };
        })) ??
      []
    );
  },
  ber: async () => {
    return [
      {
        label: "是",
        value: true
      },
      {
        label: "否",
        value: false
      }
    ];
  }
};

/**
 * 筛选字典处理
 */

const getDictIdAsyncFn = async (id: any) => {
  const data: any = await getDictIdAsync(id);
  return (
    (data &&
      data.map((item: any) => {
        return {
          label: item.name,
          value: item.value || item.id
        };
      })) ??
    []
  );
};

// 处理columns
const transformResource = (data: any) => {
  // permissionsResource
  //permissionsResourceButton
  const _filterFn = (item: any) => {
    return item.isFilter
      ? {
          type: item.fieldType,
          operator: getDictIdAsyncFn,
          fieldOperate: item.fieldOperate,
          fieldValue: item.fieldValue,
          value: (() => {
            switch (item.fieldValueType) {
              case "1": // 字典
                return getDictIdAsyncFn;
              case "2": // 接口
                return filterFnList[item?.fieldValue];
              case "3": // 自定义
                return "";
            }
          })(),
          attribute: (() => {
            const placeholder = item.fieldType === "input" ? "请输入" : "请选择";
            return {
              placeholder,
              clearable: true,
              filterable: true,
              "value-format": "YYYY-MM-DD HH:mm:ss"
            };
          })()
        }
      : false;
  };
  const columns = data
    ?.filter((item: any) => item.typeId === dict.permissionsResource)
    .map((item: any) => {
      return {
        title: item.name,
        key: item.fieldName,
        isShowSort: item.isSort,
        isSearch: false,
        filter: _filterFn(item),
        tableName: item.tableName,
        ...(tableColumnsOptions[item.fieldName] ?? {})
      };
    });
  columns.unshift({
    type: "index",
    title: "编号",
    key: "serialNumber",
    width: 46
  });
  // if (BUTTONS.includes("delete")) {
  columns.push({
    title: "操作",
    key: "option",
    width: 160,
    className: "no-padding"
  });
  // }

  // 按钮权限资源
  data
    ?.filter((item: any) => item.typeId === dict.permissionsResourceButton)
    .map((item: any) => {
      (resourceButton.value[item.componentName] = resourceButton.value[item.componentName] ?? []).push(item.perms.split(":")[2]);
    });
  return { columns };
};

// 获取所有用户
const getListAllUserApi = async () => {
  const { data } = await getListAllUser();
  userList = data || [];
};
// 获取所有控制器
const getListAllControllerApi = async () => {
  const { data } = await getProductCategoryPartAll(
    {
      typeId: getDictId("control")
    },
    { noLoading: true }
  );
  controllerList = data || [];
};

// 获取columns
const getResourceFn = async () => {
  try {
    const { data } = await getResourceByUserId({ resourceType: ORDER_KEY });
    const { columns } = transformResource(data);
    tableColumns.value = columns;
  } catch (error) {
    console.log(error);
  }
};
const formatHandler = (val: any) => {
  return val ? dayjs(val).format("YYYY年MM月DD日") : "--";
};
// api 获取数据清洗
const afterApiTransformData = (data: any) => {
  data =
    data &&
    data.map((item: any) => {
      let { order, project } = item;
      // 车型
      order.agvType = order.productCategoryList.map((itm: any) => {
        return {
          id: itm.id,
          name: itm.name || "--"
        };
      });
      // 数量
      order.agvCountCustom = order.productCategoryList.map((itm: any) => {
        return {
          id: itm.id,
          name: itm.count || "--"
        };
      });
      // 工厂
      order.productionFactoryId = order.productCategoryList.map((itm: any) => {
        return {
          id: itm.id,
          factoryId: itm.productionFactoryId || "--"
        };
      });

      // 控制器
      order.controllerId = order.productCategoryList.map((itm: any) => {
        return {
          id: itm.id,
          controllerId: itm.controllerId || "--"
        };
      });

      // 设计主负责人、电气设计 electricalDesign
      order.headOfDesign = [];
      order.electricalDesign = [];
      order.productCategoryList.map((itm: any) => {
        const headOfDesign =
          itm.projectUserList && itm.projectUserList.find((its: any) => its.typeId === getDictId("headOfDesign"));
        const electricalDesign =
          itm.projectUserList && itm.projectUserList.find((its: any) => its.typeId === getDictId("HeadOfElectricalDesign"));

        order.headOfDesign.push({
          id: headOfDesign ? headOfDesign.userId : "",
          name: headOfDesign ? headOfDesign.userName : "",
          orderProductId: itm.id,
          typeId: getDictId("headOfDesign")
        });
        order.electricalDesign.push({
          id: electricalDesign ? electricalDesign.userId : "",
          name: electricalDesign ? electricalDesign.userName : "",
          orderProductId: itm.id,
          typeId: getDictId("HeadOfElectricalDesign")
        });
      });
      // 人员
      (order.planUserId = [{ id: "", name: "", typeId: getDictId("planHead") }]),
        (order.developId = [{ id: "", name: "", typeId: getDictId("developId") }]),
        (order.supportId = [{ id: "", name: "", typeId: getDictId("supportId") }]);
      if (project) {
        project.userModels.map((item: any) => {
          if (item.typeId === getDictId("planHead")) {
            // 规划负责人
            order.planUserId = [
              {
                id: item ? item.userId : "",
                name: item ? item.userName : "",
                typeId: getDictId("planHead")
              }
            ];
          } else if (item.typeId === getDictId("developId")) {
            // 软件开发负责人
            order.developId = [
              {
                id: item ? item.userId : "",
                name: item ? item.userName : "",
                typeId: getDictId("developId")
              }
            ];
          } else if (item.typeId === getDictId("supportId")) {
            // 技术负责人
            order.supportId = [
              {
                id: item ? item.userId : "",
                name: item ? item.userName : "",
                typeId: getDictId("supportId")
              }
            ];
          }
        });
      }
      // 其余跟随车型显示的值
      AGV_MODEL_LIST.forEach((item: any) => {
        order[item] = order.productCategoryList.map((itm: any) => {
          return {
            id: itm.id,
            name: itm[item]
          };
        });
      });

      // 订单跟踪
      order.orderFollow = order.orderFollowList ?? [];
      if (project) {
        project.projectId = project.id;
        delete project.id;
        delete project.typeId;
      }
      console.log(order);
      return {
        ...order,
        ...project
      };
    });

  return data;
};

// 处理订单列表状态
const colorOrderStatus = [
  "order-table-status1",
  "order-table-status2",
  "order-table-status3",
  "order-table-status4",
  "order-table-status5"
];
const colorOrderStatusMap: any = {};
const dealOrderStatus = (list: any) => {
  return (
    (list &&
      list.map((item: any, index: number) => {
        item.className = colorOrderStatus[index];
        colorOrderStatusMap[item.id] = item.className;
        return item;
      })) ||
    []
  );
};

// 处理订单阶段状态
const colorOrderStage = [
  "order-table-stage1",
  "order-table-stage2",
  "order-table-stage3",
  "order-table-stage4",
  "order-table-stage5",
  "order-table-stage6",
  "order-table-stage7",
  "order-table-stage8"
];
const colorOrderStageMap: any = {};
const dealOrderStage = (list: any) => {
  return (
    (list &&
      list.map((item: any, index: number) => {
        item.className = colorOrderStage[index];
        colorOrderStageMap[item.id] = item.className;
        return item;
      })) ||
    []
  );
};

// 删除
const deleteOrderFn = async (params: any) => {
  await useHandleData(deleteOrder, { id: params.id }, `删除【${params.name}】`);
  tableRef.value.refresh();
};

onMounted(async () => {
  getListAllUserApi();
  getListAllControllerApi();
  await getResourceFn();
});
</script>

<style lang="scss" scoped>
.order-page {
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  gap: 20px;
  .order-table {
    width: 100%;
    height: 100%;
  }
  :deep(.wik-table-feature) {
    .wik-tools {
      flex: 0 0 72px;
      margin-bottom: 10px;
      background: #ffffff;
      .wik-tools-left-search {
        border: 1px solid #dddfe6;
        box-sizing: border-box;
        height: 32px;
        .el-icon {
          height: inherit;
        }
        .el-input__wrapper {
          box-sizing: border-box;
        }
        .el-input__inner {
          height: 28px;
          line-height: 28px;
        }
      }
    }
    .wik-table {
      background: #ffffff;
    }
    .wik-pagination {
      margin-top: 10px;
      background: #ffffff;
    }
  }
  .wik-column {
    width: 100%;
    overflow: hidden;
    .wik-column-item {
      display: flex;
      align-items: center;
      height: 45px;
      padding: 0 10px;
      overflow: hidden;
      line-height: 45px;
      text-overflow: ellipsis;
      white-space: nowrap;
      box-sizing: border-box;
      cursor: default;
      border-bottom: 1px solid #eeeeee;
      &:last-child {
        border: 0;
      }
      &:hover {
        background: var(--el-color-primary-light-9);
      }
    }
  }
  .wik-column-over-auto {
    overflow: visible;
    .wik-column-item {
      overflow: visible;
    }
  }
  // .wik-column-wrapper {
  //   display: flex;
  // }
  .wik-column-client {
    display: flex;
    flex-flow: flex-start nowrap;
    align-items: center;
    gap: 8px;
    padding: 0 10px;
    width: 100%;
    overflow: hidden;
    .el-icon {
      color: $primary-color;
    }
  }
  .wik-column-rl {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: inherit;
    padding: 6px 10px;
    cursor: pointer;
    .order-table-status {
      flex: 1;
    }
    .order-table-input {
      height: 100%;
      margin-right: 10px;
      margin-left: 0;
    }
    svg {
      display: none;
      color: #aaaaaa;
      flex: 0 0 14px;
    }
    &:hover {
      svg {
        display: block;
      }
    }
    :deep(.el-input) {
      height: 100%;
      .el-input__wrapper {
        box-shadow: none;
      }
    }
  }
  .trigger-context {
    width: inherit;
    height: inherit;
  }
  .trigger-context-status {
    display: grid;
    align-items: center;
    width: 100%;
    height: inherit;
    cursor: pointer;
  }
  .order-table-status {
    height: 22px;
    border-radius: 14px;
    border: 1px solid transparent;
    margin: 0 16px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
  }

  .order-table-status-delay {
    height: 22px;
    border-radius: 14px;
    margin: 0 16px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
    color: $order-color-2;
    width: 100%;
    background-color: $order-bg-color-2;
  }
  .order-table-status-delay_active {
    color: $order-color-5;
    background-color: $order-bg-color-5;
  }
  .order-table-head {
    margin: 0 16px;
  }
  .order-table-text {
    margin: 0 16px;
  }
  .order-table-document {
    color: $primary-color;
  }
  .wik-table-option {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .default-pointer {
    cursor: default;
    margin: 0;
    padding: 0 16px;
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    min-width: 0;
    word-break: break-all;
    box-sizing: border-box;
  }
}
</style>
<style lang="scss">
.order-detail-dialog {
  --el-dialog-padding-primary: 0;

  height: 80vh;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    height: 100%;
  }
}

// 审核状态
.order-table-status {
  &-audit1 {
    color: $order-color-1;
    background: $order-bg-color-1;
  }
  &-audit2 {
    color: $order-color-2;
    background: $order-bg-color-2;
  }
  &-audit3 {
    color: $order-color-5;
    background: $order-bg-color-5;
  }
}

// 订单状态
.order-table-status1 {
  color: $order-color-6;
  background: $order-bg-color-6;
}
.order-table-status2 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-status3 {
  color: $order-color-3;
  background: $order-bg-color-3;
}
.order-table-status4 {
  color: $order-color-2;
  background: $order-bg-color-2;
}
.order-table-status5 {
  color: $order-color-5;
  background: $order-bg-color-5;
}

// 当前阶段
.order-table-stage1 {
  color: $order-color-6;
  background: $order-bg-color-6;
}
.order-table-stage2 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage3 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage4 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage5 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage6 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage7 {
  color: $order-color-1;
  background: $order-bg-color-1;
}
.order-table-stage8 {
  color: $order-color-2;
  background: $order-bg-color-2;
}
</style>
